package com.yezao.yzrouter.touterParser

import android.content.Context
import android.util.Xml
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.*

class RouterXmlParser : IRouterParser {
    override fun parseFromRes(context: Context, resID: Int): Map<String, String> {
        val xml = context.resources.getXml(resID)
        val map = doParse(xml)
        xml.close()
        return map
    }

//    override fun parseFromFile(context: Context, path: String): Map<String, String> {
//        val parser = Xml.newPullParser()
//        parser.setInput(FileReader(File(path)))
//        return doParse(parser)
//    }

    override fun parseFromIO(context: Context, ins: InputStream): Map<String, String> {
        val parser = Xml.newPullParser()
        parser.setInput(InputStreamReader(ins))
        return doParse(parser)
    }

    private fun doParse(xmlParser: XmlPullParser): Map<String, String> {
        val map = HashMap<String, String>()

        while (xmlParser.eventType != XmlPullParser.END_DOCUMENT) {//一直读到 xml文件结束
            xmlParser.next()
            when {
                isStartOf(xmlParser, "route-item") -> {//route-item 开始标签
                    //读 route key
                    val readRoute = readText(xmlParser, "route")
                    val readClass = readText(xmlParser, "class")
                    if (readRoute != null && readClass != null) {
                        map[readRoute] = readClass
                    }
                }
                isEndOf(xmlParser, "route-item") -> {//route-item结束标签

                }
                else -> {
                    println("不关心的标签")
                }
            }
        }
        return map
    }

    private fun isStartOf(xmlParser: XmlPullParser, tag: String): Boolean {
        return if (xmlParser.eventType == XmlPullParser.START_TAG) {
            xmlParser.name == tag
        } else {
            false
        }
    }

    private fun isEndOf(xmlParser: XmlPullParser, tag: String): Boolean {
        return if (xmlParser.eventType == XmlPullParser.END_TAG) {
            xmlParser.name == tag
        } else {
            false
        }
    }

    private fun readText(xmlParser: XmlPullParser, name: String): String? {
        if (xmlParser.nextTag() != XmlPullParser.START_TAG) {// 判断开始标签
            return null
        }
        if (xmlParser.name != name) {//是否是目标标签的开始标签
            return null
        }
        if (xmlParser.next() != XmlPullParser.TEXT) {//判断是否是text 标签范围
            return null
        }
        val text = xmlParser.text

        if (xmlParser.nextTag() != XmlPullParser.END_TAG) {// 结束标签
            return null
        }
        if (xmlParser.name != name) {//是否是目标 标签的结束标签
            return null
        }
        return text
    }
}